/*
 * @lc app=leetcode.cn id=19 lang=cpp
 *
 * [19] 删除链表的倒数第 N 个结点
 */

// @lc code=start

// struct ListNode {
//     int val;
//     ListNode *next;
//     ListNode() : val(0), next(nullptr) {}
//     ListNode(int x) : val(x), next(nullptr) {}
//     ListNode(int x, ListNode *next) : val(x), next(next) {}
// };
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode *cur = head; ListNode* pre = nullptr, *now = head;
        for (int i = 1; i < n; i++) {
            if (cur != nullptr) cur = cur->next;
        }
        if (cur == nullptr) return head;
        while (cur->next != nullptr) {
            pre = now; now = now->next;
            cur = cur->next;
        }
        if (pre != nullptr) {
            pre->next = now->next; 
        } else {
            head = now->next;
        }
        delete now; now = nullptr;
        return head;
    }
};
// @lc code=end

